package org.example.repository;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class RepositoryManager {

    private final SchemaManager schemaManager;
    private final RepositoryFactory repositoryFactory;
    private final Map<String, Repository<?>> repositories = new HashMap<>();
    private final Object lock = new Object();

    public RepositoryManager(SchemaManager schemaManager, RepositoryFactory repositoryFactory) {
        this.schemaManager = schemaManager;
        this.repositoryFactory = repositoryFactory;
    }

    /**
     * get repository by schema name, or create one if not exists
     */
    @SuppressWarnings("unchecked")
    public <T extends Entity<?>> Repository<T> get(String name) {
        if (!repositories.containsKey(name)) {
            synchronized (lock) {
                if (!repositories.containsKey(name)) {
                    log.info("get repository {}", name);
                    Schema schema = schemaManager.get(name);
                    if (schema == null) {
                        throw new RuntimeException("schema not found");
                    }
                    Repository<T> repository = repositoryFactory.createRepository(schema);
                    repositories.put(name, repository);
                }
            }
        }
        return (Repository<T>) repositories.get(name);
    }
}
